package com.xps.charmingshop.view.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.liangmutian.mypicker.TimePickerDialog;
import com.jude.utils.JUtils;
import com.xps.charmingshop.R;
import com.xps.charmingshop.adapter.CollocationListAdapter;
import com.xps.charmingshop.bean.MenuBean;
import com.xps.charmingshop.bean.ShopBean;
import com.xps.charmingshop.bean.VerificationBean;
import com.xps.charmingshop.date.net.UserNetWorks;
import com.xps.charmingshop.utils.DensityUtil;
import com.xps.charmingshop.utils.SharedPreferencesUtils;
import com.xps.charmingshop.view.activity.AddMenuActivity;
import com.xps.charmingshop.view.activity.CeShiActivity;
import com.xps.charmingshop.view.activity.MapActivity;
import com.xps.charmingshop.view.activity.UpdateMenuActivity;
import com.xps.charmingshop.view.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Subscriber;

/**
 * Created by MI on 2018/1/10.
 */

public class ShopFragment extends BaseFragment {
    @BindView(R.id.Text_State)
    TextView TextState;
    @BindView(R.id.Text_Morning)
    TextView TextMorning;
    @BindView(R.id.Text_Night)
    TextView TextNight;
    @BindView(R.id.Text_Address)
    public TextView TextAddress;
    Unbinder unbinder;
    @BindView(R.id.Text_Menu)
    TextView TextMenu;
    @BindView(R.id.Text_Name)
    TextView TextName;
    @BindView(R.id.iv_State)
    ImageView ivState;
    Unbinder unbinder1;
    @BindView(R.id.iv_morning)
    ImageView ivMorning;
    @BindView(R.id.iv_night)
    ImageView ivNight;
    Unbinder unbinder2;
    private Dialog timeDialog;
    int yourChoice;
    public String AddressLat;
    public String AddressLng;
    @BindView(R.id.elv_collocation)
    ExpandableListView elvCollocation;
    List<MenuBean.ReturnBodyBean> returnBodyBeen;
    List<MenuBean.ReturnBodyBean.DishInfoBean> dishInfoBeen;

    View AddView;
    Dialog AddDialog;
    EditText Add_Name;
    EditText Add_Price;
    ViewGroup.MarginLayoutParams Addparams;
    TextView Button_Add;
    private String shopName;

    @Override
    protected int getRes() {
        return R.layout.fragment_shop;
    }

    @Override
    protected void init(View view) {
        unbinder = ButterKnife.bind(this, view);
        getShop();
        getMenu();

        AddDialog = new Dialog(getActivity(), R.style.BottomDialog);
        AddView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_addclassification, null);
        AddDialog.setContentView(AddView);
        Addparams = (ViewGroup.MarginLayoutParams) AddView.getLayoutParams();
        Addparams.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(getActivity(), 16f);
        Addparams.bottomMargin = DensityUtil.dp2px(getActivity(), 8f);
        AddView.setLayoutParams(Addparams);
        AddDialog.setCanceledOnTouchOutside(true);
        AddDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        Add_Name = AddView.findViewById(R.id.Optional_Name);
        Add_Price = AddView.findViewById(R.id.Optional_Price);
        Button_Add = AddView.findViewById(R.id.Button_Optional);
        Button_Add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Add_Name.getText().toString().equals("") || Add_Name.getText().toString() == null) {
                    JUtils.Toast("添加失败");
                } else {
                    getAddClassification();
                }
                AddDialog.dismiss();
            }
        });

    }

    @Override
    protected void setData(View view) {

    }

    @Override
    public void onClick(View v) {

    }

    public void hide() {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.hide(this);
        fragmentTransaction.commit();
    }

    void getShop() {
        String user_token = SharedPreferencesUtils.getString("user_token", "String", null);
        UserNetWorks.getShop(user_token, new Subscriber<ShopBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(ShopBean shopBean) {

                if (shopBean.getReturn_code().equals("SUCCESS")) {
                    if (shopBean.getReturn_body().getShop_status().equals("1")) {
                        TextState.setText("正常");
                    } else if (shopBean.getReturn_body().getShop_status().equals("0")) {
                        TextState.setText("待审核");
                    } else if (shopBean.getReturn_body().getShop_status().equals("2")) {
                        TextState.setText("不公开");
                    }
                    shopName = shopBean.getReturn_body().getShop_name();
                    TextName.setText(shopBean.getReturn_body().getShop_name() + "");
                    AddressLat = shopBean.getReturn_body().getShop_x();
                    AddressLng = shopBean.getReturn_body().getShop_y();
                    TextMorning.setText(shopBean.getReturn_body().getShop_open_time() + "");
                    TextNight.setText(shopBean.getReturn_body().getShop_close_time() + "");
                    TextAddress.setText(shopBean.getReturn_body().getShop_address() + "");
                }
            }
        });
    }

    void getAddClassification() {
        String user_token = SharedPreferencesUtils.getString("user_token", "String", null);
        UserNetWorks.getAddClassification(user_token, Add_Name.getText().toString(), Add_Price.getText().toString(), new Subscriber<VerificationBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();

            }

            @Override
            public void onNext(VerificationBean verificationBean) {
                if (verificationBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(verificationBean.getReturn_msg());
                    Add_Name.setText("");
                    Add_Price.setText("");
                    getShop();
                } else {
                    JUtils.Toast(verificationBean.getReturn_msg());
                }
            }
        });
    }

    public void getUpdateShop() {
        String user_token = SharedPreferencesUtils.getString("user_token", "String", null);
        String state = "1";
        if (TextState.getText().toString().equals("正常营业")) {
            state = "1";
        } else {
            state = "2";
        }

        UserNetWorks.getUpdateShop(user_token, TextName.getText().toString(), state, TextMorning.getText().toString(), TextNight.getText().toString(), TextAddress.getText().toString(), AddressLng, AddressLat, new Subscriber<VerificationBean>() {

            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(VerificationBean verificationBean) {
                if (verificationBean.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(verificationBean.getReturn_msg());
                } else {
                    JUtils.Toast(verificationBean.getReturn_msg());
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_State, R.id.Text_State, R.id.iv_morning, R.id.iv_night, R.id.Text_Address, R.id.Text_AddMenu, R.id.Text_AddClassification})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_State:
                // showSingleChoiceDialog();
                break;
            case R.id.iv_morning:
                dateDialog(TextMorning);
                break;
            case R.id.iv_night:
                dateDialog(TextNight);
                break;
            case R.id.Text_Address:
                startActivity(new Intent(getActivity(), CeShiActivity.class));
                break;
            case R.id.Text_AddMenu:
                startActivity(new Intent(getActivity(), AddMenuActivity.class));
                break;
            case R.id.Text_AddClassification:
                AddDialog.show();
                break;
        }
    }

    public void dateDialog(final TextView textView) {
        if (timeDialog == null) {
            TimePickerDialog.Builder builder = new TimePickerDialog.Builder(getActivity());
            timeDialog = builder.setOnTimeSelectedListener(new TimePickerDialog.OnTimeSelectedListener() {
                @Override
                public void onTimeSelected(int[] times) {
                    if (times[1] == 0) {
                        textView.setText(times[0] + ":00");
                    } else {
                        textView.setText(times[0] + ":" + times[1]);
                    }
                    getUpdateShop();
                }
            }).create();
        }
        timeDialog.show();
    }

    private void showSingleChoiceDialog() {
        final String[] items = {"正常营业", "停止营业"};
        yourChoice = -1;
        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(getActivity());
        singleChoiceDialog.setTitle("请选择营业状态");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (yourChoice != -1) {
                            TextState.setText(items[yourChoice] + "");
                            getUpdateShop();
                        }
                    }
                });
        singleChoiceDialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        getShop();
        getMenu();
    }

    public void getMenu() {
        String user_token = SharedPreferencesUtils.getString("user_token", "String", null);
        UserNetWorks.getMenu(user_token, new Subscriber<MenuBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(MenuBean menuBean) {
                returnBodyBeen = new ArrayList<>();
                dishInfoBeen = new ArrayList<>();

                if (menuBean.getReturn_code().equals("SUCCESS")) {
                    MenuBean.ReturnBodyBean shopInfobean = new MenuBean.ReturnBodyBean();
                    String sortName = shopInfobean.getSort_name();
                    //分类列表
                    List<MenuBean.ReturnBodyBean> list = menuBean.getReturn_body();
                    for (int i = 0; i < list.size(); i++) {
                        MenuBean.ReturnBodyBean bean = new MenuBean.ReturnBodyBean();
                        bean.setSort_name(list.get(i).getSort_name());
                        //分类里的菜品
                        List<MenuBean.ReturnBodyBean.DishInfoBean> list1 = list.get(i).getDish_info();
                        String img = null;
                        for (int k = 0; k < list1.size(); k++) {
                            MenuBean.ReturnBodyBean.DishInfoBean bean1 = new MenuBean.ReturnBodyBean.DishInfoBean();
                            bean1.dish_name = list1.get(k).getDish_name();
                            dishInfoBeen.add(bean1);
                        }
                        returnBodyBeen.add(bean);
                        //添加每一种类型的菜品
                        bean.setDish_info(list1);
                        elvCollocation.setAdapter(new CollocationListAdapter(getActivity(), elvCollocation, returnBodyBeen));
                        elvCollocation.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                            @Override
                            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                                Intent intent = new Intent(getActivity(), UpdateMenuActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.putExtra("dish_id", returnBodyBeen.get(groupPosition).getDish_info().get(childPosition).getDish_id());
                                intent.putExtra("shop_name", shopName);
                                startActivity(intent);
                                return false;
                            }
                        });
                    }
                }
            }
        });
    }
}
